﻿using System;
using System.Diagnostics;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Prism.Events;
using WeiboPlus.Models;
using WeiboPlus.Service;
using WeiboPlus.Service.Event;

namespace WeiboPlus
{
    public class AuthorizeHelper
    {
        public static void NewRequestToken(SNSProviderType t, Action<SNSAccount, SNSResult> action)
        {
            if (t == SNSProviderType.Unknow)
            {
                t = GetDefaultPlatform();
            }
            var account = AccountManager.Current.CreateAccount(t);
            var service = PhoneApplicationController.Current.Container.Resolve<IOAuthService>(account.ServiceProvider.ToString());

            if (service.Account == null)
            {
                service.ProviderResolver = () => SNSProviderManager.GetFactory(account).GetProvider();
                service.FactoryResolver = () => SNSProviderManager.CreateFactory(account);
                service.Account = account;
            }

            service.RequestToken((a, result) =>
            {
                Debug.WriteLine("OAuthToken: {0}", account.OAuthToken);
                Debug.WriteLine("OAuthTokenSecret: {0}", account.OAuthTokenSecret);
                Debug.WriteLine("AuthorizeURL: {0}", account.AuthorizeURL);
                if (action != null)
                {
                    action(a, result);
                }
                else
                {
                    if (!result.IsSuccess)
                        MessageBox.Show(result.Message);
                    else
                        PhoneApplicationController.Current.Container.Resolve<IEventAggregator>().GetEvent<NavigationRequestEvent>().Publish(new NavigationContext() { Destination = new Uri("/Views/AuthPage.xaml", UriKind.RelativeOrAbsolute), SimpleParameter = account.AccountID });
                }

            });
        }

        private static SNSProviderType GetDefaultPlatform()
        {
            return SNSProviderType.Sina;
        }
    }
}
